package cn.just.student_mall.controller;

import cn.just.student_mall.entity.User;
import cn.just.student_mall.service.UserService;
import cn.just.student_mall.service.ex.InsertException;
import cn.just.student_mall.service.ex.PasswordNotMatchException;
import cn.just.student_mall.service.ex.UserNotFoundException;
import cn.just.student_mall.service.ex.UsernameDuplicateException;
import cn.just.student_mall.util.JsonResult;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @Author wujiaming
 * @Description TODO
 * @Date 2021-03-24 15:33
 * @Version 1.0
 */

@RequestMapping("users")
@RestController
public class UserController {

    @Resource
    UserService userService;

    /**
     * 成功状态值
     */
    public static final Integer OK = 2000;

    /**
     * 请求路径/users/reg
     * @param user
     * @return
     */
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user){
        JsonResult<Void> json = new JsonResult<>();
        try{
            userService.regist(user);
            json.setState(OK);
        }catch (UsernameDuplicateException e){
            json.setState(0);
            json.setMessage("注册失败，用户名已占用");
        }catch(InsertException e){
            json.setState(-1);
            json.setMessage("注册失败，插入数据异常，联系管理员");
        }

        return json;
    }

    /**
     * 请求路径 /users/login
     * @param username
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        try{
            User  u = userService.login(username, password);

            //登录成功后 保存用户信息到session中
            session.setAttribute("uid",u.getUid());
            session.setAttribute("username",u.getUsername());
            return new JsonResult<User>(OK,u);
        }catch (UserNotFoundException e){
            e.printStackTrace();
            return new JsonResult<>(0,"登录失败，用户名不存在");
        }catch(PasswordNotMatchException e){
            e.printStackTrace();
            return new JsonResult<>(-1,"登录失败，密码不正确");
        }


    }

    /**
     * /user/avatar/change
     * 返回数据中包含的新图片的路径
     * @param file
     * @param session
     * @return
     */
    @RequestMapping("avatar/change")
    public JsonResult<String> changeAvatar(MultipartFile file,HttpSession session){
        //获取原始文件名
        String oldFileName = file.getOriginalFilename();
        System.out.println(oldFileName);

        //将文件上传到指定文件夹
        //获取tomcat部署后在本地的目录
        String parent = session.getServletContext().getRealPath("upload");
        System.out.println("upload path=" + parent);

        //创建保存图片的目录
        File dir = new File(parent);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //保存上传文件使用的文件名 :img0.jpg ----》img0+times.jpg
        //获取当前时间的毫秒
        long time = System.currentTimeMillis();
        //后缀
        String suffix = "";
        int beginIndex = oldFileName.lastIndexOf(".");
        //.jpg
        suffix = oldFileName.substring(beginIndex);
        String newFileName = oldFileName.substring(0,beginIndex) + time + suffix;
        //将客户端得到的文件保存到服务器中
        File dest = new File(parent,newFileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new JsonResult<>("上传失败，读写文件异常请联系管理员");
        }
        //将文件路径保存到数据库  /upload/newFileName
        String avatar = "/upload/" + newFileName;
        System.out.println("avatar path" + avatar);
        Integer uid = (Integer)session.getAttribute("uid");
        String username = (String)session.getAttribute("username");
        userService.changeAvatar(uid,username,avatar);
        JsonResult<String> json = new JsonResult<>(OK);
        json.setData(avatar);
        return json;
    }
}
